import moment from 'moment';
import {getLocalData,gotoRouter} from './common';
import {appname} from '../config';
import * as global from '../global';

export default {
  isPhoneNumber(phone)
  {
    let rule = /^1([38]\d|4[57]|5[0-35-9]|7[06-8]|8[89])\d{8}$/;
    return rule.test(phone);
  },
  getCurrentMonth()
  {
    if(moment().isBetween(global.appdata.startTime,global.appdata.endTime))
    {
      return moment().format('YYYY-MM');
    }
    else
    {
      return moment(global.appdata.endTime).format('YYYY-MM');
    }
  },
  goBack()
  {
    history.go(-1);
  },
  onMenu(pathname,dispatch)
  {
    let query = { month: global.appdata.selected_month };
    gotoRouter(dispatch,pathname);
  },
  formatNumber(num)
  {
    if(num == undefined)
    {
      return '0.00';
    }
    let s_number = num + '';
    if(s_number.indexOf('.') == -1)
    {
      s_number += '.00';
    }
    let s_arr = [];
    let len = s_number.length;
    for(let i = len - 3;i > 0;i -= 3)
    {
      let start = i - 3;
      if(start < 0)
      {
        start = 0;
      }
      s_arr.push(s_number.slice(start,i));
    }
    let s = s_arr.reverse().join(',') + s_number.slice(len - 3,len);
    return s;
  },
  GetRequest()
  {
    let url = location.search;
    let theRequest = new Object();
    if(url.indexOf("?") != -1)
    {
      let str = url.substr(1);
      let strs = str.split("&");
      for(let i = 0;i < strs.length;i++)
      {
        theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
      }
    }
    return theRequest;
  },
  saveAppData()
  {
    localStorage.setItem(appname,JSON.stringify(global.appdata));
  }
}